package com.powernode.config;

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器
 * 作用: 解决服务之间调用没有token的情况
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * @param requestTemplate 即将要发起新的请求的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //判断是否有值
        if (ObjectUtil.isNotNull(requestAttributes)) {
            // 获取当前请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            //判断是否有值
            if (ObjectUtil.isNotNull(request)) {
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION, authorization);
                return;
            }
        }
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "e94c4a66-09b4-4f5e-987c-ab97f8a3cb72");
    }
}